<template>
  <aside class="ls" :class="{ 'is-collapsed': collapsed }">
    <div class="ls__header">
      <img src="/logo.jpg" class="ls__logo" alt="WuWaManus" />
      <h1 class="ls__title" v-if="!collapsed">WuWaManus</h1>
    </div>

    <div class="ls__scroll">
      <button class="ls__new-chat" @click="emitNewChat">
        <svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/></svg>
        <span v-if="!collapsed">开启新对话</span>
      </button>

      <!-- 对话历史列表 -->
      <ul class="conversation-list" v-if="!collapsed">
        <li
          v-for="conv in conversations"
          :key="conv.chatId"
          class="conversation-item"
          :title="conv.message"
          @click="onSelectConversation(conv.chatId)"
        >
          <span class="conversation-text">
            {{ truncate(conv.message, 15) || '（空消息）' }}
          </span>
          <!-- 删除对话按钮:鼠标悬浮修改高亮颜色 -->
          <div 
            class="delete-conversation"
            @click.stop="onDeleteConversation(conv.chatId)" 
            title="删除对话"
          >
            🗑️
          </div>
        </li>
      </ul>
    </div>

    <!-- 个人信息区域 - 固定在底部 -->
    <div class="ls__profile" @click="toggleMenu">
      <img :src="userAvatar" class="profile__avatar" alt="avatar"/>
      <div class="profile__meta" v-if="!collapsed">
        <div class="profile__name">{{ userName || '个人信息' }}</div>
      </div>
      <!-- 个人信息菜单 -->
      <div class="profile__menu" v-if="menuOpen" @click.stop>
        <button class="menu__item" @click="emitViewProfile">个人信息</button>
        <button class="menu__item menu__danger" @click="emitLogout">退出登录</button>
      </div>
    </div>
    <!-- 折叠按钮 -->
    <button class="ls__toggle" @click="toggle" :aria-label="collapsed ? '展开侧边栏' : '收起侧边栏'">
      <svg v-if="collapsed" viewBox="0 0 24 24" width="18" height="18">
        <path fill="currentColor" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
      </svg>
      <svg v-else viewBox="0 0 24 24" width="18" height="18"><path fill="currentColor" d="M14 6l1.41 1.41L10.83 12l4.58 4.59L14 18l-6-6z"/></svg>
    </button>
  </aside>
</template>

<script setup>
import { ref, computed,watch } from 'vue';
import { useConversationStore } from '../stores/conversation';


const props = defineProps({
  initialCollapsed: { type: Boolean, default: false },
  user: { type: Object, default: () => ({}) }
});
const emit = defineEmits(['logout', 'view-profile', 'toggle', 'new-chat', 'select-conversation', 'delete-conversation']);

const collapsed = ref(props.initialCollapsed);
const menuOpen = ref(false);
//从 Pinia 中获取对话历史列表
const conversationStore = useConversationStore();
// 替换原有的conversations和loadConversations
const conversations = computed(() => conversationStore.conversations);

const userAvatar = computed(() => props.user?.userAvatar || '/user-avatar.svg');
const userName = computed(() => props.user?.userName || props.user?.userAccount || '个人信息');


function toggle() {
  collapsed.value = !collapsed.value;
  emit('toggle', collapsed.value);
}
function toggleMenu() { menuOpen.value = !menuOpen.value; }
function handleOutside(e) {
  const container = e.target.closest?.('.ls__profile');
  if (!container) menuOpen.value = false;
}
function emitLogout() { menuOpen.value = false; emit('logout'); }
function emitViewProfile() { menuOpen.value = false; emit('view-profile'); }
function emitNewChat() {
   emit('new-chat'); 
}

function truncate(text, maxLen = 15) {
  const s = String(text || '').trim();
  if (!s) return '';
  return s.length > maxLen ? s.slice(0, maxLen) + '…' : s;
}

function onSelectConversation(chatId) {
  emit('select-conversation', chatId);
}

function onDeleteConversation(chatId){
  emit('delete-conversation', chatId);
}
/**
 * 当切换登录用户后，根据用户 ID 重新加载对话历史
 */
watch(() => props.user, () => {
  const uid = props.user?.id || props.user?.userId;
  if (uid) {
    conversationStore.loadConversations(uid);
  }
}, { deep: true, immediate: true });

</script>

<style scoped>
.ls {
  position: relative;
  width: 200px;
  background: #f7f8fa;
  border-right: 1px solid var(--border-color);
  transition: width .2s ease;
  height: calc(100vh);
  display: flex;
  flex-direction: column;
  overflow: visible;
}
.ls.is-collapsed { width: 64px; }

.ls__header {
  display: flex; align-items: center; gap: 12px; padding: 16px;
  border-bottom: 1px solid var(--border-color);
}
.ls__logo { width: 28px; height: 28px; border-radius: 50%; }
.ls__title { font-size: 16px; font-weight: 600; margin: 0; color: var(--text-primary); }

.ls__scroll {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 12px;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.ls__new-chat {
  display: flex; align-items: center; gap: 8px; padding: 10px 12px;
  background: #fff; border: 1px solid var(--border-color); border-radius: 8px;
  color: var(--text-primary); cursor: pointer; font-size: 14px;
  margin-bottom: 16px;
}
.ls__new-chat:hover { background: #f5f6f7; }

.conversation-list { 
  list-style: none; padding: 0; margin: 0 0 12px 0;
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  min-height: 0;
}

/* 自定义滚动条样式 */
.conversation-list::-webkit-scrollbar {
  width: 6px;
}

.conversation-list::-webkit-scrollbar-track {
  background: transparent;
}

.conversation-list::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
}

.conversation-list::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}
.conversation-item { 
  padding: 8px 10px; margin-bottom: 8px; cursor: pointer; 
  background: #fff; border: 1px solid var(--border-color); border-radius: 6px; 
  font-size: 13px; color: var(--text-primary);
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 36px;
}
.conversation-item:hover { background: #f5f6f7; }  

.conversation-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
}

.delete-conversation {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  font-size: 14px;
  opacity: 0.6;
  transition: all 0.2s ease;
  flex-shrink: 0;
  margin-left: 8px;
}

.delete-conversation:hover { 
  background: #fee2e2;
  color: #dc2626;
  opacity: 1;
  transform: scale(1.1);
}

.conversation-item:hover .delete-conversation {
  opacity: 1;
}

.ls__profile {
  margin-top: auto;
  position: relative;
  display: flex; align-items: center; gap: 12px; padding: 8px;
  border-radius: 8px; cursor: pointer;
}

.ls__profile:hover { background: rgba(0,0,0,.04); }
.profile__avatar { width: 32px; height: 32px; border-radius: 50%; border: 1px solid var(--border-color); }
.profile__name { font-size: 14px; color: var(--text-secondary); }

.profile__menu {
  position: absolute; bottom: 52px; left: 8px; background: #fff; border: 1px solid var(--border-color);
  border-radius: 8px; box-shadow: 0 16px 24px rgba(0,0,0,.06); padding: 6px; 
  width: 160px;
}
.menu__item { width: 100%; text-align: left; padding: 8px 8px; border-radius: 6px; border: none; background: transparent; cursor: pointer; text-align: center;}
.menu__item:hover { background: #f5f6f7; }
.menu__danger { color: #ef4444; }

.ls__toggle {
  position: absolute; right: -14px; top: 17px; z-index: 10;
  width: 28px; height: 28px; border-radius: 50%;
  background: #fff; border: 1px solid var(--border-color);
  display: grid; place-items: center; cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
</style>